﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Security.Cryptography;
using System.IO;
using System.Text;

using CE.Global;
using CE.Image;
using CE.User;
using CE.Mail;
public partial class user_password_recovery : MyLanguageBasePage
{
    protected override void InitializeCulture()
    {
        String selectedCulture = CE.Global.General.SetCulture();
        base.InitializeCulture();
    }

    string _redirectUrl = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        Master.Page.Title = Resources.Title.PasswordRecoveryTitle;
        if (Session[CE.Global.General.UserId] != null && Session[CE.Global.General.UserTypeId] != null)
        {
            if (Convert.ToInt32(Session[CE.Global.General.UserTypeId]) ==
                Convert.ToInt32(CE.Global.CEUserType.Customer))
            {
                _redirectUrl = CE.Global.General.GetUrl("~/", Page);
                Response.Redirect(_redirectUrl);
            }
        }

        if (Session["ImageCount"] != null)
        {
            if (Convert.ToInt32(Session["ImageCount"].ToString()) > 5)
            {
                btnSubmit.Enabled = false;
                btnNewImage.Enabled = false;
                txtEmail.Enabled = false;
                txtSecurityCode.Enabled = false;
                Response.Redirect("user-message?mt=UM&ec=1993");
            }
            else
            {
                btnSubmit.Enabled = true;
                btnNewImage.Enabled = true;
                txtEmail.Enabled = true;
                txtSecurityCode.Enabled = true;
            }
        }

        if (!Page.IsPostBack)
        {
            Session["UMMSG"] = null;
            LogUserViewedHistory();

            if (Session["ImageCount"] != null)
            {
                if (Convert.ToInt32(Session["ImageCount"].ToString()) <= 5)
                {
                    CreateUpdateImageAndSession();
                }
            }
            else
            {
                CreateUpdateImageAndSession();
            } 
            txtEmail.Attributes.Add("onblur", "ShowValidationEffectTwo('" + txtEmail.ClientID + "','" + rfvEmail.ClientID + "','" + revEmail.ClientID + "');");
            txtSecurityCode.Attributes.Add("onblur", "ShowValidationEffect('" + txtSecurityCode.ClientID + "','" + rfvSecurityCheck.ClientID + "');");
            
        }
    }

    private void LogUserViewedHistory()
    {
        UserViewHistoryDB _userviewdb = new UserViewHistoryDB();
        _userviewdb.LogViewedHistory("PWR", Request, "User password recovery.");
    }

    private void CreateUpdateImageAndSession()
    {
        MyImage myimage = new MyImage();
        string salt = "";

        if (Session[CE.Global.General.SecurityCheckWord] != null)
        {
            salt = myimage.GetRandomWord(Session[CE.Global.General.SecurityCheckWord].ToString());
        }
        else
        {
            if (Session[CE.Global.General.SecurityCheckWord] != null)
            {
                salt = myimage.GetRandomWord(Session[CE.Global.General.SecurityCheckWord].ToString());
            }
            else
            {
                salt = myimage.GetRandomWord("all");
            }
        }
        Session[CE.Global.General.SecurityCheckWord] = salt;
        imgCAPTCHA.ImageUrl = @"/CAPTCHA/CAPTCHAImageHandler.ashx?id=" + CE.Security.MySecurity.Encrypt(salt, true);
        txtSecurityCode.Text = "";
    }

    protected void btnNewImage_Click(object sender, EventArgs e)
    {
        CreateUpdateImageAndSession();
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        try
        {
            ChangeValidationEffectServerSide("customer");
            Page.Validate("customer");
            if (Page.IsValid)
            {
                if (Session[CE.Global.General.SecurityCheckWord] != null)
                {
                    string _usrText = txtSecurityCode.Text.ToUpper();
                    string _imgText = Session[CE.Global.General.SecurityCheckWord].ToString().ToUpper();
                    if (_usrText == _imgText)
                    {
                        AccountDB _accountdb = new AccountDB();
                        Account _account = _accountdb.GetUserAccount(txtEmail.Text, Convert.ToInt32(CE.Global.CEUserType.Customer));
                        if (_account != null)
                        {
                            string salt = CE.Security.MySecurity.Encrypt(Session[CE.Global.General.SecurityCheckWord].ToString(), true);
                            string strGUID = _accountdb.GetGUID(_account.CEID);
                            salt = salt.Replace("+", "");
                            _account.AuthSalt = salt;
                            if (_accountdb.Insert(_account) > 0)
                            {
                                string _customerName = "";
                                ProfileDB _profiledb = new ProfileDB();
                                Profile _profile = _profiledb.GetProfile(_account.CEID);
                                if (_profile != null)
                                {
                                    if (_profile.FirstName != null && _profile.FirstName != string.Empty)
                                    {
                                        _customerName = Server.HtmlDecode(_profile.FirstName) + " " + Server.HtmlDecode(_profile.SurName);
                                    }
                                    else
                                    {
                                        _customerName = Server.HtmlDecode(_profile.SurName);
                                    }
                                }
                                if (MyMailManager.SendPasswordResetLink(_customerName, _account.Email, salt, strGUID, CE.Global.CEUserType.Customer))
                                {
                                    _redirectUrl = CE.Global.General.GetUrl("~/user/user-message", Page);
                                    Session["UMMSG"] = "UMG,199";
                                    Response.Redirect(_redirectUrl);
                                }
                                else
                                {
                                    lblMessage.Text = Resources.ErrorMessage.EmailFail;
                                }
                            }
                            else
                            {
                                lblMessage.Text = Resources.ErrorMessage.PasswordCreateFaild; 
                            }
                        }
                        else
                        {
                            lblMessage.Text = Resources.UserMessage.NoEmailFound;
                        }
                    }
                    else
                    {
                        lblMessage.Text = Resources.UserMessage.WrongSecurityCheck;
                        CreateUpdateImageAndSession();
                    }
                }
                else
                {
                    lblMessage.Text = Resources.ErrorMessage.SecurityCodeExpired;
                    CreateUpdateImageAndSession();
                }
            }
        }
        catch (Exception ex)
        {
        }
    }

    public string CreateSalt(int size)
    {
        RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
        Byte[] buff = new Byte[size];
        rng.GetBytes(buff);

        return Convert.ToBase64String(buff);
    }

    private void ChangeValidationEffectServerSide(string strValidationGroup)
    {
        txtEmail.Text = HttpUtility.HtmlEncode(txtEmail.Text);
        txtSecurityCode.Text = HttpUtility.HtmlEncode(txtSecurityCode.Text);

        //Email
        if (rfvEmail.Enabled && rfvEmail.ValidationGroup == strValidationGroup)
        {
            rfvEmail.Validate();
            if (rfvEmail.IsValid == false)
            {
                txtEmail.ControlStyle.CssClass = "input-fields validationError";
            }
            else
            {
                txtEmail.ControlStyle.CssClass = "input-fields";
            }
        }
        else
        {
            txtEmail.ControlStyle.CssClass = "input-fields";
        }

        if (revEmail.Enabled && revEmail.ValidationGroup == strValidationGroup)
        {
            if (rfvEmail.IsValid)
            {
                revEmail.Validate();
                if (revEmail.IsValid == false)
                {
                    txtEmail.ControlStyle.CssClass = "input-fields validationError";
                }
                else
                {
                    txtEmail.ControlStyle.CssClass = "input-fields";
                }
            }
        }
        else
        {
            txtEmail.ControlStyle.CssClass = "input-fields";
        }

        //Feed back
        if (rfvSecurityCheck.Enabled && rfvSecurityCheck.ValidationGroup == strValidationGroup)
        {
            rfvSecurityCheck.Validate();
            if (rfvSecurityCheck.IsValid == false)
            {
                txtSecurityCode.ControlStyle.CssClass = "input-fields validationError";
            }
            else
            {
                txtSecurityCode.ControlStyle.CssClass = "input-fields";
            }
        }
        else
        {
            txtSecurityCode.ControlStyle.CssClass = "input-fields";
        }

    }

}
